import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Checkbox, Balloon } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import intl from '../../../../../../../../../../locale';

const { Group: CheckboxGroup } = Checkbox;
const FormItem = Form.Item;

const TRIGGER = {
  PUSH_EVENTS: 'push_events',
  MERGE_REQUESTS_EVENTS: 'merge_requests_events',
  TAG_PUSH_EVENTS: 'tag_push_events',
  COMMENTS: 'note_events',
};

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class ProjectModal extends React.Component {
  static propTypes = {
    closeModal: PropTypes.func,
  };

  static defaultProps = {
    closeModal: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
    };
  }

  componentDidMount() {
    this.props.getOneHook(this.props.id, (result) => {
      const events = [];
      if (result.push_events) {
        events.push('push_events');
      }
      if (result.tag_push_events) {
        events.push('tag_push_events');
      }
      if (result.note_events) {
        events.push('note_events');
      }
      if (result.merge_requests_events) {
        events.push('merge_requests_events');
      }
      // 保存编辑项原先的url, 不和自身做重复校验
      this.selfUrl = result.url;
      this.field.setValues({
        url: result.url,
        events,
        description: result.description || '',
        secret_token: result.secret_token || '',
      });
    });
  }

  URLValidator = (rule, value, callback) => {
    const { webhooks } = this.props;
    if (
      !value ||
      /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/.test(value)
    ) {
      if (value === this.selfUrl) {
        callback();
        return;
      }
      webhooks
        .filter((v) => v.type !== 'OrganizationHook')
        .forEach((item) => {
          if (item.url === value) {
            callback(
              intl.get({
                id: 'code-assets.containers.editWebhooks.editDialog.TheSpecifiedUrlAlreadyExists',
                defaultMessage: 'URL 已存在',
              }),
            );
          }
        });
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.containers.editWebhooks.editDialog.TheUrlParameterIsInvalid',
          defaultMessage: 'URL 参数不合法',
        }),
      );
    }
  };

  onClose = () => {
    this.props.closeModal();
  };

  handleOk = () => {
    if (this.state.submitting) return;
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        formData.push_events = formData.events.includes(TRIGGER.PUSH_EVENTS);
        formData.merge_requests_events = formData.events.includes(TRIGGER.MERGE_REQUESTS_EVENTS);
        formData.tag_push_events = formData.events.includes(TRIGGER.TAG_PUSH_EVENTS);
        formData.note_events = formData.events.includes(TRIGGER.COMMENTS);
        this.props.edit(this.props.id, formData, (isFail) => {
          if (!isFail) {
            this.field.reset();
          }
          this.setState({ submitting: false });
          this.onClose();
        });
      }
    });
  };

  onEventChane = (selectedItems) => {
    this.field.setValue('events', selectedItems);
  };

  messageValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 200) {
      callback(
        intl.get({
          id: 'code-assets.containers.editWebhooks.editDialog.TheDescriptionCannotExceedCharacters',
          defaultMessage: '描述长度不能超过200',
        }),
      );
    } else {
      callback();
    }
  };

  render() {
    const { init } = this.field;
    return (
      <Dialog
        title={
          <div>
            {intl.get({
              id: 'code-assets.containers.editWebhooks.editDialog.EditingWebhook',
              defaultMessage: '编辑 Webhook',
            })}
          </div>
        }
        visible
        style={{ width: '600px' }}
        onOk={this.handleOk}
        onCancel={this.onClose}
        onClose={this.onClose}
        footerActions={['cancel', 'ok']}
        okProps={{ loading: this.state.submitting }}
        className="edit-webhook-dialog"
      >
        <Form {...formItemLayout} field={this.field} labelAlign="top">
          <FormItem label="URL" required>
            <Input
              maxLength={1024}
              hasLimitHint
              autoFocus
              {...init('url', {
                rules: [
                  {
                    required: true,
                    message: intl.get({
                      id: 'code-assets.containers.editWebhooks.editDialog.ThisParameterIsRequired',
                      defaultMessage: '该项为必填项',
                    }),
                  },

                  {
                    validator: this.URLValidator,
                  },
                ],
              })}
            />
          </FormItem>
          <FormItem
            label={
              <div>
                Secret Token
                <Balloon.Tooltip
                  trigger={
                    <ButtonIcon
                      name="question-line"
                      style={{ marginLeft: 4, display: 'inline-block' }}
                    />
                  }
                  popupStyle={{
                    width: 470,
                    maxWidth: 'none',
                  }}
                  align="t"
                >
                  {intl.get({
                    id: 'code-assets.containers.editWebhooks.editDialog.TheRequestIsSentIn',
                    defaultMessage:
                      '在请求的 X-Codeup-Token HTTP头中发送，用于接收方验证请求合法性',
                  })}
                </Balloon.Tooltip>
              </div>
            }
          >
            <Input
              maxLength={100}
              hasLimitHint
              placeholder={intl.get({
                id: 'code-assets.containers.editWebhooks.editDialog.EnterAToken',
                defaultMessage: '请输入 Token',
              })}
              {...init('secret_token')}
            />
          </FormItem>
          <FormItem
            label={intl.get({
              id: 'code-assets.containers.editWebhooks.editDialog.Trigger',
              defaultMessage: '触发器',
            })}
            {...formItemLayout}
            required
          >
            <CheckboxGroup
              onChange={this.onEventChane}
              {...init('events', {
                rules: [
                  {
                    required: true,
                    message: intl.get({
                      id: 'code-assets.containers.editWebhooks.editDialog.ThisParameterIsRequired',
                      defaultMessage: '该项为必填项',
                    }),
                  },
                ],
              })}
            >
              <Checkbox id={TRIGGER.PUSH_EVENTS} value={TRIGGER.PUSH_EVENTS}>
                {intl.get({
                  id: 'code-assets.containers.editWebhooks.editDialog.PushEvents',
                  defaultMessage: '推送事件',
                })}
              </Checkbox>
              <Checkbox id={TRIGGER.TAG_PUSH_EVENTS} value={TRIGGER.TAG_PUSH_EVENTS}>
                {intl.get({
                  id: 'code-assets.containers.editWebhooks.editDialog.TagPushEvent',
                  defaultMessage: '标签推送事件',
                })}
              </Checkbox>
              <Checkbox id={TRIGGER.COMMENTS} value={TRIGGER.COMMENTS}>
                {intl.get({
                  id: 'code-assets.containers.editWebhooks.editDialog.Comments',
                  defaultMessage: '评论',
                })}
              </Checkbox>
              <Checkbox id={TRIGGER.MERGE_REQUESTS_EVENTS} value={TRIGGER.MERGE_REQUESTS_EVENTS}>
                {intl.get({
                  id: 'code-assets.containers.editWebhooks.editDialog.MergeRequestEvents',
                  defaultMessage: '合并请求事件',
                })}
              </Checkbox>
            </CheckboxGroup>
          </FormItem>
          <FormItem
            label={intl.get({
              id: 'code-assets.containers.editWebhooks.editDialog.Description',
              defaultMessage: '描述',
            })}
            {...formItemLayout}
          >
            <Input.TextArea
              {...init('description', {
                rules: [{ validator: this.messageValidator }],
              })}
              placeholder={intl.get({
                id: 'code-assets.containers.editWebhooks.editDialog.EnterADescription',
                defaultMessage: '请输入描述',
              })}
            />
          </FormItem>
        </Form>
      </Dialog>
    );
  }
}
